package com.multiThread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class CountDownLatchDemo {


    public static void main(String[] args) {
        int threadNum = 5;
        // 一、用CountDownLatch实现多个线程都就绪后一起开始的功能：但不建议这样使用，最好是使用CyclicBarrier
        CountDownLatch countDonw = new CountDownLatch(threadNum);
        for (int i = 0; i < threadNum; i++)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        countDonw.countDown();
                        // 调用await方法的线程都会阻塞，直到count计算器为0。所以都会等到最后一个线程准备好了才开始
                        countDonw.await();
                        // 模拟业务操作，这里只是打印线程名称
                        System.out.println("CountDownLatch "+ Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        System.out.println("================这里是分割线===============");

        // 二、用CyclicBarrier实现多个线程都就绪后一起开始的功能
        CyclicBarrier cb = new CyclicBarrier(threadNum);
        for (int i = 0; i < threadNum; i++)
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        Thread.sleep(3000);// 模拟线程启动耗时
                        cb.await();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    // 模拟业务操作，这里只是打印线程名称
                    System.out.println("CyclicBarrier "+Thread.currentThread().getName());

                }
            }).start();
    }
}
